package extension.game.poker;

import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;
import extension.poker.zone.Flag;
import java.util.List;
import log.Debug;

public class OnUserGoneHandler extends BaseServerEventHandler {
    
    @SuppressWarnings("unchecked")
    @Override
    public void handleServerEvent(ISFSEvent event) throws SFSException {
        User user = (User) event.getParameter(SFSEventParam.USER);
        PokerRoomExtension pokerRoomExtension = (PokerRoomExtension) getParentExtension();
        PokerGame pokerGame = pokerRoomExtension.getPokerGame();
        PokerPlayer[] listPlayers = pokerGame.getListPlayers();
        int leaveId = -1;
        for (int i = 0; i < listPlayers.length; i++) {
            if (listPlayers[i] != null) {
                if (listPlayers[i].getUser().getId() == user.getId()) {
                    leaveId = i;
                }
            }
        }
        if (user != null) {
            pokerGame.removePlayer(user);
        }
        if (leaveId != -1) {
            pokerRoomExtension.getResponse().sendUserLeave(leaveId, pokerGame.getIsPlay());
            if (leaveId == pokerGame.getBettingTurn()) {
                pokerGame.nextTurn();
            }
            pokerRoomExtension.getResponse().sendMessageChat(user.getName() + " rời bàn", 0);
            sendUpdate(pokerRoomExtension, user);
        }
    }
    
        private void sendUpdate(PokerRoomExtension ext, User userExit) {
            Room room = ext.getParentRoom();
            String groupName = room.getGroupId();
            Room lobbyRoom = ext.getParentZone().getRoomByName("The Lobby");
    //        List<Room> listRooms = ext.getParentZone().getRoomListFromGroup(groupName);
            List<User> listSend = lobbyRoom.getUserList();
            listSend.remove(userExit);
            for (User u : listSend) {
                Debug.d("send update to :" + u.getName());
                String groupView = (String) u.getProperty(Flag.GROUP_NAME);
                if (groupView.equals(groupName)) {
                    ext.getResponse().sendUpdateTable(room.getName(), ext.getPokerGame().getNumberPlayers(), room.getGroupId(), u);
                }
            }
        }
}
